package com.yangguang.huahui.ui.activitys;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.HyphenateException;
import com.yangguang.huahui.R;
import com.yangguang.huahui.app.App;
import com.yangguang.huahui.entity.DataInfo;
import com.yangguang.huahui.entity.HttpResult;
import com.yangguang.huahui.entity.Login;
import com.yangguang.huahui.mvp.model.CommonModel;
import com.yangguang.huahui.rx.RxManager;
import com.yangguang.huahui.rx.RxSubscriber;
import com.yangguang.huahui.utils.CommonUtil;
import com.yangguang.huahui.utils.LogUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import butterknife.BindView;
import butterknife.OnClick;

public class DetailActivity extends BaseActivity {
    @BindView(R.id.mWebView)
    WebView mWebView;
    @BindView(R.id.tv_title)
    TextView tv_title;
    private String webUrl = "";
    private String id = "";
    private int type;//50=个人详情，1=客户需求，8=苗木，9=花卉，10=农资，23=农机
    private String detail_type = "1";

    @BindView(R.id.pb)
    ProgressBar pb;
    @BindView(R.id.mLL_operat)
    LinearLayout mLL_operat;

    @OnClick({R.id.iv_back, R.id.iv_collect, R.id.iv_share})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
                break;
            case R.id.iv_collect:
                collect(DataInfo.TOKEN, type, id);
                break;
            case R.id.iv_share:
                break;
        }
    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_detail;
    }

    @Override
    protected void initView() {
        App.getInstance().addActivity((Activity) mContext);
        webUrl = getIntent().getStringExtra("webUrl");
        id = getIntent().getStringExtra("id");
        type = getIntent().getIntExtra("type", 0);
        detail_type = getIntent().getStringExtra("detail_type");
        initWebView();
    }

    @Override
    protected void initData() {
        pb.setMax(100);
    }

    @SuppressLint("NewApi")
    private void initWebView() {
//        mWebView.clearCache(true);
//        mWebView.clearHistory();

        // 为WebView设置WebViewClient处理某些操作
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);// 支持javascript
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        // TODO 导入错误
//         settings.setPluginsEnabled(true);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setAllowFileAccess(true);
        settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setDefaultTextEncodingName("UTF-8");
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setLoadsImagesAutomatically(true);
        settings.setBlockNetworkImage(false);
        //设置 缓存模式
//        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        // 开启 DOM storage API 功能
//        settings.setGeolocationEnabled(true);
//        settings.setGeolocationDatabasePath(getFilesDir().getPath());
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();

        //启用地理定位
        settings.setGeolocationEnabled(true);
        //设置定位的数据库路径
        settings.setGeolocationDatabasePath(dir);


        mWebView.setBackgroundColor(0);
        switch (type) {
            case 50:
                webUrl = webUrl + "?uid=" + id + "&for_id=" + DataInfo.TOKEN;
                mLL_operat.setVisibility(View.GONE);
                break;
        }
        LogUtil.e(webUrl, true);
        mWebView.loadUrl(webUrl + "?id=" + id);
        mWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtil.e(url, true);
                // TODO Auto-generated method stub
                // 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
//                view.loadUrl(url);
                if (url.startsWith("scheme:") || url.startsWith("scheme:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                if (url.contains("chat")) {
                    String userId = url.replace("next://chat:", "");
                    if (CommonUtil.isNull(userId)) {
                        CommonUtil.myToastA(mContext, "信息为空");
                    } else {
                        if (CommonUtil.isNull(DataInfo.TOKEN)) {
                            startActivity(new Intent(mContext, LoginActivity.class));
                        } else {
                            startActivity(new Intent(mContext, ChatActivity.class)
                                    .putExtra("userId", userId)
                                    .putExtra("id", id)
                                    .putExtra("detail_type", detail_type));
                        }
                    }
                    return true;
                }
                if (url.contains("connection")) {
                    phone = url.replace("next://connection:", "");
                    requestPermission(new String[]{Manifest.permission.CALL_PHONE}, 0x0001);
                    return true;
                }
                if (url.contains("black")) {
                    final String to_uid = url.replace("next://black:", "");
                    if (CommonUtil.isNull(DataInfo.TOKEN)) {
                        startActivity(new Intent(mContext, LoginActivity.class));
                    } else {
                        RxManager.getInstance().doSubscribe(new CommonModel().add_to_black(to_uid, DataInfo.TOKEN), new RxSubscriber<HttpResult>(false) {
                            @Override
                            protected void _onNext(HttpResult httpResult) {
                                CommonUtil.myToastA(mContext, httpResult.getMsg());
                                EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
                                String action = "huahui";//action可以自定义
                                EMCmdMessageBody cmdBody = new EMCmdMessageBody(action);
                                String toUsername = to_uid;//发送给某个人
                                cmdMsg.setTo(toUsername);
                                cmdMsg.addBody(cmdBody);
                                EMClient.getInstance().chatManager().sendMessage(cmdMsg);
                            }

                            @Override
                            protected void _onError() {

                            }
                        });
                    }
                    return true;
                }
                if (url.startsWith("baidumap:")) {
                    if (CommonUtil.isClientInstalled(mContext, "com.baidu.BaiduMap")) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    } else {
                        CommonUtil.myToastA(mContext, "您还没安装百度地图");
                    }
                    return true;
                }

                if (url.contains("information")){
                    type = 50;
                    mLL_operat.setVisibility(View.GONE);
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                pb.setVisibility(View.VISIBLE);
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                pb.setVisibility(View.GONE);
                if (type != 50) {
                    mLL_operat.setVisibility(View.VISIBLE);
                }
                super.onPageFinished(view, url);
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                super.onShowCustomView(view, callback);
                view.draw(new Canvas());
            }
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                pb.setProgress(newProgress);
                if (newProgress >= 100) {
                    pb.setVisibility(View.GONE);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title_1) {
                tv_title.setText(title_1);
                super.onReceivedTitle(view, title_1);
            }

            @Override
            public void onGeolocationPermissionsHidePrompt() {
                super.onGeolocationPermissionsHidePrompt();
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setMessage("是否允许获取地理位置?");
                DialogInterface.OnClickListener dialogButtonOnClickListener = new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int clickedButton) {
                        if (DialogInterface.BUTTON_POSITIVE == clickedButton) {
                            callback.invoke(origin, true, true);
                        } else if (DialogInterface.BUTTON_NEGATIVE == clickedButton) {
                            callback.invoke(origin, false, false);
                        }
                    }
                };
                builder.setPositiveButton("允许", dialogButtonOnClickListener);
                builder.setNegativeButton("拒绝", dialogButtonOnClickListener);
                builder.show();
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }
        });


        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            type = getIntent().getIntExtra("type", 0);
            mLL_operat.setVisibility(View.VISIBLE);
        } else {
            finish();
        }
    }

    String phone = "";

    @Override
    public void permissionSuccess(int requestCode) {
        super.permissionSuccess(requestCode);
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        phone = "";
    }
}
